<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      div {
        margin: 0 auto;
        position: relative;
      }
      p {
        position: absolute;
      }
    </style>
  </head>
  <body>
    <div style="width: 800px; height: 400px; background: pink">
      <p style="width: 20px; height: 20px; background: peru"></p>
      <p id="w" style="width: 20px; height: 20px; background: green"></p>
      <script>
        function randomnum(min, max) {
          return parseInt(Math.random() * (max - min + 1) + min);
        }
        function createFood() {
          var foods = document.querySelector("#w");
          foods.style.left = `${randomnum(100, 700)}px`;
          foods.style.top = `${randomnum(50, 350)}px`;
          console.log(foods.style.left);
        }
        createFood();
        var pEle = document.querySelector("p");
        var speed = 4;
        var str = "left";
        document.onkeydown = function (e) {
          var e = e || window.e;
          //每次按键都需要设置方向 后面根据str去设置对应的偏移量
          if (e.key == "ArrowRight") {
            str = "left";
            speed = Math.abs(speed);
          }
          if (e.key == "ArrowLeft") {
            str = "left";
            speed = -Math.abs(speed);
          }

          if (e.key == "ArrowUp") {
            str = "top";
            speed = -Math.abs(speed);
          }
          if (e.key == "ArrowDown") {
            str = "top";
            speed = Math.abs(speed);
          }
          console.log(str);
        };
        setInterval(function () {
          var nowIn = parseInt(pEle.offsetLeft);
          if (str == "top") {
            nowIn = parseInt(pEle.offsetTop);
          }
          pEle.style[str] = nowIn + speed + "px";
        }, 50);
      </script>
    </div>
  </body>
</html>
